package com.stu.widget;

import com.stu.info.GraphFragment;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Align;
import android.util.AttributeSet;
import android.view.View;

public class VerLabelsView extends View {
	private String[] vlabels;
	private float min, max;
	private boolean scaleChanged;
	private Paint vTextPaint;
	private int textHeight;
	private GraphFragment graphFragment;
	private int gridY;
	
	public VerLabelsView( Context c ) {
		super( c );
		init();
	}

	public VerLabelsView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	
	public VerLabelsView(Context context, AttributeSet attrs, int defaultStyle) {
		super(context, attrs, defaultStyle);
		init();
	}

	private void init() {
		gridY = GraphView.GraphViewConfig.GRID_Y;
		graphFragment = null;
		vTextPaint = new Paint();
		vTextPaint.setColor( GraphView.GraphViewConfig.LABEL_COLOR );
		vTextPaint.setTextAlign(Align.LEFT);

		Rect r = new Rect();
		vTextPaint.getTextBounds( "1", 0, 1, r );
		textHeight = r.height();
		vlabels = new String[gridY + 1];
		reset();
	}

	public void setFragment( GraphFragment f ) {
		graphFragment = f;
	}

	public void setGrid( int y ) {
		gridY = y;
		vlabels = new String[gridY + 1];
		reset();
	}
	
	public void reset() {
		min = 0;
		max = gridY;
		scaleChanged = true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if( graphFragment == null )
			return;

		if( graphFragment.maxY > gridY ) {
			max = graphFragment.maxY;
			scaleChanged = true;
		}
		if( graphFragment.minY < min ) {
			min = graphFragment.minY;
			scaleChanged = true;
		}

		int h = getHeight();
		if( scaleChanged ) {
			float dy = (1.0f / (float)gridY) * (max - min);
			float val = min;
			for (int i = 0; i <= gridY; i++) {
				vlabels[i] = GraphFragment.formatLabel(val, false);
				val += dy;
			}
			scaleChanged = false;
		}
		float dy = h / gridY;
		float y = h;
		for (int i = 0; i <= gridY; i++) {
			if( i == 0 )
				canvas.drawText(vlabels[i], 0, y-textHeight, vTextPaint);
			else if( i == gridY )
				canvas.drawText(vlabels[i], 0, y+textHeight, vTextPaint);
			else
				canvas.drawText(vlabels[i], 0, y, vTextPaint);
			y -= dy;
		}
	}
}
